package com.yueqianshop.order.controller;

import com.alibaba.fastjson.JSON;
import com.yueqianshop.common.exception.NoStockException;
import com.yueqianshop.order.service.OrderService;
import com.yueqianshop.order.vo.OrderConfirmVo;
import com.yueqianshop.order.vo.OrderSubmitResponseVo;
import com.yueqianshop.order.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.jws.WebParam;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderservice;

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {

        OrderConfirmVo orderConfirmVo = orderservice.orderConfirm();
        model.addAttribute("data",orderConfirmVo);
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes){

        try{
            OrderSubmitResponseVo orderSubmitResponseVo = orderservice.submitOrder(orderSubmitVo);
            System.out.println(orderSubmitVo);
            if(orderSubmitResponseVo.getCode() == 0){
                model.addAttribute("submitOrderResp", orderSubmitResponseVo);
                return "pay";
            }else {
                String msg = "下订单失败";
                switch (orderSubmitResponseVo.getCode()){
                    case 1 : msg+="订单信息过期，请刷新后再次提交";break;
                    case 2 : msg+="订单中的商品价格发生变化, 请刷新后再次提交.";break;
                    case 3 : msg+="库存锁定失败, 商品库存不足";break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.yueqianshop.com/toTrade";
            }
        }catch (Exception e){
            if(e instanceof NoStockException){
                String message = e.getMessage();
                redirectAttributes.addFlashAttribute("msg" , message);

            }
            return "redirect:http://order.yueqianshop.com/toTrade";
        }



    }
}
